"use client";
import { useRef, useState, useEffect } from "react";
import { request } from "@/utils/request";
import { PagedDataResponse, CommentInfo, MsgResponse } from "@/type";
import { filterField } from "@/utils/filterField";
import DisplayComment from "./DisplayComment";

type Props = {
  articleId: number;
};

export interface TempCommentInfo extends CommentInfo {
  isHover: boolean;
}

const maxWords = 2000;
const repliedInfo = {
  parentId: null as number | null,
  repliedNickname: null as string | null,
};

export default function Comments({ articleId }: Props) {
  const [words, setWords] = useState(0);
  const [commentStr, setCommentStr] = useState("");
  const contentRef = useRef<HTMLTextAreaElement>(null);
  const [commentList, setCommentList] = useState<CommentInfo[]>([]);

  function getCommentList() {
    request<PagedDataResponse<CommentInfo>>(
      `/comments?articleId=${articleId}`
    ).then((res) => {
      if (res?.data) setCommentList(res?.data.list);
    });
  }
  useEffect(() => {
    getCommentList();
  }, [articleId, getCommentList]);

  function inputContent(e: React.ChangeEvent<HTMLTextAreaElement>) {
    if (e.target.value.length <= maxWords) {
      setCommentStr(e.target.value);
      setWords(e.target.value.length);
    }
  }

  function postComment() {
    if (commentStr.length === 0) return;
    let tempCommentStr = commentStr;
    if (repliedInfo.repliedNickname) {
      const regex = new RegExp(`^@${repliedInfo.repliedNickname}\\s*`);
      tempCommentStr = tempCommentStr.replace(regex, "");
    }
    const postCommentInfo = filterField({
      ...repliedInfo,
      articleId,
      commentNickname: "test",
      commentEmail: "123@qq.com",
      comment: tempCommentStr,
    });
    request<MsgResponse>("/comment", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(postCommentInfo),
    })
      .then((res) => {
        if (res?.code === 0) {
          setCommentStr("");
          repliedInfo.parentId = null;
          repliedInfo.repliedNickname = null;
        }
      })
      .catch((err) => {
        console.log("发布评论失败", err);
      })
      .finally(() => {
        getCommentList();
      });
  }

  function clickReplied(parentId: number | null, commentNickname: string) {
    repliedInfo.parentId = parentId;
    repliedInfo.repliedNickname = commentNickname;
    setCommentStr(
      `@${repliedInfo.repliedNickname} ${commentStr.replace(/^@\S+\s*/, "")}`
    );
    if (contentRef.current) {
      contentRef.current.scrollIntoView({
        behavior: "smooth",
        block: "center",
      });
      setTimeout(() => {
        contentRef.current?.focus();
      });
    }
  }

  useEffect(() => {
    if (
      repliedInfo.repliedNickname &&
      !commentStr.startsWith(`@${repliedInfo.repliedNickname} `)
    ) {
      repliedInfo.parentId = null;
      repliedInfo.repliedNickname = null;
    }
    setWords(commentStr.length);
  }, [commentStr]);

  return (
    <>
      {/* 发送评论 */}
      <div className="border bg-primary-foreground border-stone-800 rounded-lg overflow-hidden">
        <textarea
          ref={contentRef}
          value={commentStr}
          rows={7}
          placeholder="畅所欲言哦~~~"
          className="w-full p-3 bg-primary-foreground resize-none focus:outline-none"
          onChange={inputContent}
        />
        <div className="flex justify-between items-center m-2">
          {words} / {maxWords}
          <button
            onClick={postComment}
            className="border rounded-[10px] px-2 p-1 bg-primary-card"
          >
            发送 📤
          </button>
        </div>
      </div>
      {/* 展示评论 */}
      <div className="my-5 md:my-10">
        {commentList.map((item) => (
          <div key={item.comment_id} className="mb-5 md:mb-7">
            {/* 父评论 */}
            <DisplayComment commentInfo={item} clickReplied={clickReplied} />

            {/* 子评论示意 */}
            {item.replies && item.replies?.length > 0 && (
              <div className="ml-5 md:ml-10">
                {item.replies.map((child) => (
                  <DisplayComment
                    key={child.comment_id}
                    commentInfo={child}
                    clickReplied={clickReplied}
                  />
                ))}
              </div>
            )}
          </div>
        ))}
      </div>
    </>
  );
}
